import axios from "axios";
import { Base64 } from "js-base64";
import { ElMessage, ElMessageBox } from 'element-plus'

// 创建通用axios配置
let instance = axios.create({
    responseType: 'json',// 返回json格式
    headers: { 'Content-Type': 'application/json' }
})

// 对token加密
function baseFun() {
    const token = localStorage.getItem('token')
    const base64 = Base64.encode(token + ':') //对token加密
    return 'Basic ' + base64
}

// http拦截 实在axios请求发出之前给每一个接口携带token去后端校验身份
instance.interceptors.request.use(
    config => {
        let token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = baseFun()
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

// http拦截  在axios请求发出之后
instance.interceptors.response.use(
    response => {
        return response
    },
    error => {
        if (error.response) {
            let ERRS = error.response.status
            let MSG = error.response.data.msg.msg
            let errData = ERRS === 401 ? MSG : '服务器发生错误'
            switch (ERRS) {
                case 401:
                    //  没有访问权限
                    ElMessageBox.alert(errData, '提示', {
                        confirmButtonText: '好的',
                        type:'error',
                    })
                    .then(res =>{
                        // 跳转到登录界面
                        window.location.href = '/'
                    })
                    .catch(err =>{
                        window.location.href = '/'
                    })
                    break;
            }
        }
        // 返回接口错误信息
        return Promise.reject(error.response.data)
    }
)

export default instance